/*
 * Copyright (c) 2013, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.omorphdb.core.value;

/**
 * Class encapsulating type information of a document attribute.
 */
class PrimitiveValue<T> implements Value<T>
{
	private final ValueType type;
	private final T value;

	private final Class<?> jType;

	private final int size;

	/**
	 * Creates a primitive type.
	 * 
	 * @param value
	 * @param type
	 * @param size The size should always be: the size of byte, which indicates
	 *        the type of the value, then the real length of the buffer of bytes
	 *        encoding the value.
	 */
	PrimitiveValue(T value, ValueType type, int size)
	{
		this.value = value;
		this.type = type;

		this.jType = value.getClass();

		this.size = size;
	}

	@Override
	public ValueType getType()
	{
		return this.type;
	}

	@Override
	public Class<?> getJavaType()
	{
		return this.jType;
	}

	@Override
	public T get()
	{
		return this.value;
	}

	@Override
	public int size()
	{
		return this.size;
	}

	@Override
	public boolean equals(Object value)
	{
		if (value instanceof PrimitiveValue)
		{
			Value<?> value2 = (Value<?>) value;
			return value != null && this.value.equals(value2.get());
		}

		return false;
	}

	@Override
	public boolean isNull()
	{
		return this.type == null;
	}

	@Override
	public PrimitiveValue<T> clone()
	{
		return new PrimitiveValue<T>(this.value, this.type, this.size);
	}
}
